//
//  RecordManager.m
//  phonebook
//
//  Created by dyang26 on 10/10/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "RecordManager.h"
#define PATH [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/names.plist"]

@implementation RecordManager

+ (RecordManager *)sharedManager {
    static RecordManager *manager = nil;
    
    if (!manager) {
        manager = [[RecordManager alloc] init];
        [manager loadRecords];
    }
    
    return manager;
}
- (NSString *)nameOfContactAtIndex:(int)index {
	return [[self profileAtIndex:index] valueForKey:@"name"];
}
- (NSString *)phoneNumberOfContactAtIndex:(int)index {
	return [[self profileAtIndex:index] valueForKey:@"phone number"];
}
- (NSString *)addressOfContactAtIndex:(int)index {
	return [[self profileAtIndex:index] valueForKey:@"home address"];
}
- (NSString *)emailOfContactAtIndex:(int)index {
	return [[self profileAtIndex:index] valueForKey:@"email"];
}
- (NSString *)imageURLOfContactAtIndex:(int)index {
    return [[self profileAtIndex:index] valueForKey:@"image"];
}
- (NSMutableDictionary *)profileAtIndex:(int)index {
	if (![[records objectAtIndex:index] isKindOfClass:[NSMutableDictionary class]]) {
		// make it into a mutable dictionary
		[records replaceObjectAtIndex:index withObject:[[records objectAtIndex:index] mutableCopy]];
	}
	return [records objectAtIndex:index];
}

- (int) indexOfContact:(NSMutableDictionary *)contact {
    return [records indexOfObject:contact];
}
- (NSMutableArray *)names {
    return records;
}
- (int) numberOfContact {
    return [records count];
}
- (NSMutableDictionary *) createNewContact {
    NSMutableDictionary *newContact = [[NSMutableDictionary alloc] init];
    [newContact setValue:@"-1" forKey:@"index"];
    [newContact setValue:@"new contact" forKey:@"name"];
	[newContact setValue:@"new number" forKey:@"phone number"];
    [newContact setValue:@"new address" forKey:@"home address"];
    [newContact setValue:@"new email" forKey:@"email"];
    [newContact setValue:@"defaultPerson.jpg" forKey:@"image"];
	return [newContact autorelease];
}
- (void)removeRecord:(NSMutableDictionary*)record {
    records = [[NSMutableArray arrayWithContentsOfFile:PATH] retain];
    [records removeObjectAtIndex:[self indexOfContact:record]];
    [records writeToFile:PATH atomically:YES];
}

- (void)loadRecords {
    records = [[NSMutableArray arrayWithContentsOfFile:PATH] retain];
    
    if (!records) {
        records = [[NSMutableArray alloc] init];  // very important
    }
    NSLog(@"%@", PATH);
}

- (void)saveNewRecords:(NSMutableDictionary *)newContact {
    
    NSLog(@"%@", NSHomeDirectory());
    NSLog(@"%@", records);
    
    [records addObject:newContact];
    [records writeToFile:PATH atomically:YES];
}
- (void)saveRecords {
    // SAVE
    [records writeToFile:PATH atomically:YES];
}

@end
